package com.maomao.controller;

import com.maomao.config.WebSecurityConfig;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author xiaomin
 * @date 2018/4/26
 */
@Controller
public class LoginController {

    @GetMapping("/")
    public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String account, Model model) {
        model.addAttribute("name",account);
        return "index";
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session.getAttribute(WebSecurityConfig.SESSION_KEY)!=null){
            return "redirect:/";
        }

        return "login";
    }
    @PostMapping("/loginPost")
    @ResponseBody
    public Map<String,Object> loginPost(String account, String password, HttpSession session) {
        Map<String ,Object> map = new HashMap<>(8);
        if (!"123456".equals(password)) {
            map.put("success",false);
            map.put("message","密码错误");
            return map;
        }
        session.setAttribute(WebSecurityConfig.SESSION_KEY,account);
        map.put("success",true);
        map.put("message","登录成功");
        return map;
    }
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(WebSecurityConfig.SESSION_KEY);
        return "redirect:/login";
    }
}
